package com.andnux.android.adapter;

import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;

import com.andnux.android.MainApp;
import com.andnux.android.activity.BaseActivity;
import com.andnux.android.activity.ChatActivity;
import com.andnux.android.activity.CommentActivity;
import com.andnux.android.data.ChatSession;
import com.andnux.android.data.Orders;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.data.Works;
import com.andnux.android.databinding.ItemMyOrderBinding;
import com.andnux.android.dialog.DialogFactory;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.GsonUtils;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.SuccessConsumer;
import com.andnux.android.utils.ImageLoader;
import com.google.gson.reflect.TypeToken;

import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MyOrderAdapter extends BaseAdapter<Orders, ItemMyOrderBinding> {

    private final BaseActivity<?> activity;
    private final SystemUsers users;
    private DesignCloudApi api;
    private final String[] status = new String[]{"已下单", "已支付", "已发货", "待评价", "已评价"};

    public MyOrderAdapter(BaseActivity<?> activity) {
        this.activity = activity;
        users = MainApp.getApp().getSystemUsers();
        api = RetrofitClient.getInstance().getServerApi();
    }

    /**
     * 状态（0已下单 1已支付 2已发货 3待评价 4已评价）
     */

    @Override
    public void onBindView(ItemMyOrderBinding binding, Orders orders, int position) {
        super.onBindView(binding, orders, position);

        if ("2".contentEquals(users.getRole())) {
            ImageLoader.load(orders.getBuyUser().getAvatar(), binding.header);
            binding.username.setText(orders.getBuyUser().getNickname());
            binding.chat.setText("联系买家");
        } else {
            ImageLoader.load(orders.getSellUser().getAvatar(), binding.header);
            binding.username.setText(orders.getSellUser().getNickname());
            binding.chat.setText("联系卖家");
        }
        binding.status.setText(status[orders.getStatus()]);

        String json = orders.getWorks().getFiles();
        List<String> files = GsonUtils.gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        ImageLoader.load(files.get(0), binding.worksImage);
        binding.worksTitle.setText(orders.getWorks().getTitle());
        binding.worksPrice.setText(orders.getPrice());

        binding.chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Works works = orders.getWorks();
                chatSessionInsert(works, orders);
            }
        });


        binding.changePrice.setVisibility(("2".contentEquals(users.getRole()) && orders.getStatus() == 0) ? View.VISIBLE : View.GONE);

        binding.changePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showInputDialog(activity, "修改价格",
                        orders.getPrice(), "请输入价格",
                        new DialogFactory.OnEditInputClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, String content) {
                                try {
                                    Double.parseDouble(content);
                                } catch (Exception e) {
                                    Toast.makeText(activity, "价格错误", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                orders.setPrice(content);
                                orderUpdate(orders);
                                notifyItemChanged(position);
                            }
                        });
            }
        });

        binding.doPay.setVisibility(("1".contentEquals(users.getRole()) && orders.getStatus() == 0) ? View.VISIBLE : View.GONE);

        binding.doPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showNormalDialog(activity, "支付",
                        "请问您是否支付？", new DialogFactory.OnSingleClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                orders.setStatus(1);
                                orderUpdate(orders);
                                notifyItemChanged(position);
                            }
                        });
            }
        });

        binding.doSend.setVisibility(("2".contentEquals(users.getRole()) && orders.getStatus() == 1) ? View.VISIBLE : View.GONE);

        binding.doSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showNormalDialog(activity, "发货",
                        "请问您是否发货？", new DialogFactory.OnSingleClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                orders.setStatus(2);
                                orderUpdate(orders);
                                notifyItemChanged(position);
                            }
                        });
            }
        });


        binding.doDelivery.setVisibility(("1".contentEquals(users.getRole()) && orders.getStatus() == 2) ? View.VISIBLE : View.GONE);

        binding.doDelivery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFactory.showNormalDialog(activity, "收货",
                        "请问您是否收到货？", new DialogFactory.OnSingleClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                orders.setStatus(3);
                                orderUpdate(orders);
                                notifyItemChanged(position);
                            }
                        });
            }
        });

        binding.doComment.setVisibility(("1".contentEquals(users.getRole()) && orders.getStatus() == 3) ? View.VISIBLE : View.GONE);

        binding.doComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, CommentActivity.class);
                intent.putExtra("orders", orders);
                activity.startActivity(intent);
            }
        });
    }

    private void orderUpdate(Orders vo) {
        activity.addDisposable(api.orderUpdate(vo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SuccessConsumer<Result<Orders>>() {
                    @Override
                    public void onSuccess(Result<Orders> result) {
                        Toast.makeText(activity, "修改成功", Toast.LENGTH_SHORT).show();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        if (throwable != null) {
                            Toast.makeText(activity, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void chatSessionInsert(Works works, Orders orders) {
        api = RetrofitClient.getInstance().getServerApi();
        ChatSession session = new ChatSession();
        session.setCreateTime(new Date());
        SystemUsers users = MainApp.getApp().getSystemUsers();
        session.setCreator(String.valueOf(users.getId()));
        session.setFromId(String.valueOf(users.getId()));
        session.setToId(works.getUserId());
        session.setWorksId(String.valueOf(works.getId()));
        session.setDeleted("0");
        session.setMessage(users.getNickname() + "发起了会话");
        session.setToBeReadMessCount(0);
        session.setWorks(works);
        session.setFromUser(users);
        if ("2".contentEquals(users.getRole())) {
            session.setToUser(works.getUsers() == null ? orders.getBuyUser() : works.getUsers());
        } else {
            session.setToUser(works.getUsers() == null ? orders.getSellUser() : works.getUsers());
        }
        activity.addDisposable(api.chatSessionInsert(session)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SuccessConsumer<Result<String>>() {
                    @Override
                    public void onSuccess(Result<String> result) {
                        session.setSessionId(result.getData());
                        session.setWorks(works);
                        doChat(session);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(activity,
                                    throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void doChat(ChatSession session) {
        Intent intent = new Intent(activity, ChatActivity.class);
        intent.putExtra("session", session);
        activity.startActivity(intent);
    }
}
